<template>
  <div>
    <el-radio-group
      v-if="isRadio"
      v-model="id"
      :disabled="disabled == undefined ? false : disabled"
      filterable
      :placeholder="defaultMsg ? defaultMsg : '请选择'"
      :clearable="clearable == undefined ? true : clearable"
    >
      <el-radio
        v-for="item in options"
        border
        :key="item.id"
        :label="item.dictValue"
        >{{ item.dictLabel }}</el-radio
      >
    </el-radio-group>
    <el-select
      v-else
      v-model="id"
      :disabled="disabled == undefined ? false : disabled"
      filterable
      :placeholder="defaultMsg ? defaultMsg : '请选择'"
      :clearable="clearable == undefined ? true : clearable"
      :multiple="isMultiple"
    >
      <el-option
        v-for="item in options"
        :key="item.id"
        :label="item.dictLabel"
        :value="item.dictValue"
      ></el-option>
    </el-select>
  </div>
</template>
<script>
export default {
  data() {
    return {
      options: [],
      id: this.selectDict,
      statusValue: this.statusValue,
      isMultiple: this.multiple == undefined ? false : this.multiple,
    };
  },
  props: [
    "selectDict", //选中数据用于同步
    "isRadio",    //是否为单选框
    "defaultMsg", //默认提示
    "defaultValue",//默认value
    "multiple",    //是否多选(仅为下拉框时有效)
    "disabled",    //是否禁用
    "dictType",    //字典编码(在字典管理找)
    "clearable",   //是否可以清除(默认为true)
  ],
  watch: {
    id: {
      handler(val) {
        this.$emit("update:selectDict", val);
      },
      immediate: false, //首次绑定的时候，是否执行handler,此处不需要
      deep: true, //深度监听
    },
    selectDict(val) {
      this.id = val;
    },
  },
  mounted: function () {
    this.list();
  },
  methods: {
    list() {
      this.$http({
        url: this.$http.adornUrl(`/sys/sysdictdata/dataByType`),
        method: "get",
        params: this.$http.adornParams({
          dictType: this.dictType,
        }),
      }).then(( {data} ) => {
        if (data && data.code === 200) {
          this.options = data.data;
          if (this.options.length > 0 && this.defaultValue == 0) {
            this.id = this.options[0].value;
          }
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    getValue() {
      //获取选择中的值
      return this.id;
    },
    getObj() {
      //获取选择的对象
      let obj = this.options.find((item, index) => {
        if (this.id == item.value) {
          item.index = index;
          return item;
        }
      });
      return obj;
    },
  },
};
</script>
